import cTitle from "components/title";
import { Toast } from "vant";
export default {
  data() {
    return {
      classifyShow: false, //选择分类弹窗
      hoursShow: false, //选择时间弹窗
      addressShow: false, //选择地址弹窗
      applyShow: false,
      applyText: "",
      applyDescName: "", //消费券别名
      applyTextStatus: 0,
      strShow: false, //选择街道
      classifyIndex: 0, //一级分类索引
      secondIndex: null, //二级分类索引
      threeIndex: null, //三级分类索引
      uploadUrl: "upload.uploadPic", //上传图片
      anotherImgList: [],
      form: {
        store_name: "",
        //门店分类级ID
        first_category_id: 0,
        second_category_id: 0,
        third_category_id: 0,
        //省市区街道的ID和地址和定位地址
        province_id: 0,
        city_id: 0,
        district_id: 0,
        street_id: 0,
        address: "",
        longitude: "",
        latitude: "",
        //营业日(星期),
        work_week: [],
        work_start_time: "",
        work_end_time: "",
        //店铺信息，企业执照
        store_mobile: "",
        staff_name: "",
        business_name: "",
        business_pics: "",
        another_pics: [],
        identity_front_image: "",
        identity_back_image: "",
        owner_name: "",
        owner_mobile: "",
        //商户简介
        store_desc: "",
        store_banner: "",
        store_logo: ""
      },
      //门店分类ID信息
      firstCategoryItem: {},
      secondCategoryItem: {},
      thirdCategoryItem: {},
      CategoryName: "",
      classifyList: [], //商户分类
      secondLevel: [],
      threeLevel: [],
      //地址信息
      addressName: "",
      streetName: "", //街道地址
      mapdataAddress: "", //定位地址信息
      streetShow: false,
      //选择时间功能
      timeState: 1, //判断是选择开始时间还是结束时间
      businessHours: "",
      workWeek: [
        //显示选中的日期数组
        {
          title: "周一",
          value: "1",
          checked: false
        },
        {
          title: "周二",
          value: "2",
          checked: false
        },
        {
          title: "周三",
          value: "3",
          checked: false
        },
        {
          title: "周四",
          value: "4",
          checked: false
        },
        {
          title: "周五",
          value: "5",
          checked: false
        },
        {
          title: "周六",
          value: "6",
          checked: false
        },
        {
          title: "周日",
          value: "7",
          checked: false
        }
      ],
      checkedAll: false,
      selectImgIndex: "",
      stopButton: false,
      currentTime: "0:00",
      startTime: "0:00",
      endTime: "0:00",

      //街道
      area: district
    };
  },
  activated() {
    this.uploadUrl = this.fun.getRealUrl("upload.uploadPic", {});
    this.storeApply(); //商户申请协议
    this.categoryList();
    this.fun
      .getLocation()
      .then(res => {
        let p = this.fun.bd_encrypt(res.point.lng, res.point.lat);
        this.form.latitude = p.lng;
        this.form.longitude = p.lat;
        this.mapdataAddress = res.title;
      })
      .catch(err => {
        console.log(err);
      });
    // self = this;
  },
  methods: {
    _initData() {
      let query = {
        store_name: "", //门店分类级ID
        first_category_id: 0,
        second_category_id: 0,
        third_category_id: 0,
        //省市区街道的ID和地址和定位地址
        province_id: 0,
        city_id: 0,
        district_id: 0,
        street_id: 0,
        address: "",
        longitude: "",
        latitude: "",
        //营业日(星期),
        work_week: [],
        work_start_time: "",
        work_end_time: "",
        //店铺信息，企业执照
        store_mobile: "",
        staff_name: "",
        business_name: "",
        business_pics: "",
        another_pics: [],
        identity_front_image: "",
        identity_back_image: "",
        owner_name: "",
        owner_mobile: "",
        //商户简介
        store_desc: "",
        store_banner: "",
        store_logo: ""
      };
      this.CategoryName = "";
      this.addressName = "";
      this.form = query;
    },
    onStair(...query) {
      //点击一级分类，获取下级分类;
      const [index, item] = [...query];
      let secondLevelArr = []; //空数组
      if (item.has_many_child.length > 0) {
        secondLevelArr = item.has_many_child; //空数组
      }
      this.classifyInit(index, item, secondLevelArr);
    },
    onSecond(...query) {
      //查询二级分类下面的分类
      const [index, item] = [...query];
      let threeLevelArr = [];
      if (item.has_many_child.length > 0) {
        threeLevelArr = item.has_many_child;
      }
      this.secondIndex = index;
      this.threeLevel = threeLevelArr;
      this.secondCategoryItem = item;
    },
    onThreeLevel(...query) {
      //三级分类
      const [index, item] = [...query];
      this.threeIndex = index;
      this.thirdCategoryItem = item;
    },
    onClose(type) {
      if (type === "hours") {
        this.hoursShow = false;
      } else {
        this.classifyShow = false;
      }
    },
    onAddress() {
      this.addressShow = true;
    },
    // 地址回调
    addressCallback(obj) {
      this.addressName = obj.itemName1 + " " + obj.itemName2 + " " + obj.itemName3;

      this.form.province_id = obj.itemValue1;

      this.form.city_id = obj.itemValue2;

      this.form.district_id = obj.itemValue3;

      this.getStreet(obj.itemValue3);
    },
    // 获取街道
    getStreet(param) {
      $http
        .get("member.memberAddress.street", { district_id: param })
        .then(response => {
          if (response.result === 1) {
            if (!this.fun.isTextEmpty(response.data) && response.data.length > 0) {
              this.districtVal = response.data;
              this.strShow = true;
            } else {
              this.strShow = false;
            }
          } else {
            this.strShow = false;
          }
        })
        .catch(error => {
          console.log(error);
        });
    },
    applyPopup() {
      if (this.applyTextStatus) {
        this.applyShow = true;
      }
    },
    applyClose() {
      this.applyShow = false;
    },
    streetShowbtn() {
      this.streetShow = true;
    },
    streetConfirm(item) {
      this.streetName = item.areaname;
      this.form.street_id = item.id;
      this.streetShow = false;
    },
    onclassifyAffirm() {
      //商户分类提交
      if (this.firstCategoryItem.id && this.secondCategoryItem.id && this.thirdCategoryItem.id) {
        let classifyNmae = `${this.firstCategoryItem.name}/${this.secondCategoryItem.name}/${this.thirdCategoryItem.name}`;
        this.form.first_category_id = this.firstCategoryItem.id;
        this.form.second_category_id = this.secondCategoryItem.id;
        this.form.third_category_id = this.thirdCategoryItem.id;
        this.CategoryName = classifyNmae;
        this.classifyShow = false;
      } else {
        Toast("请选择分类");
        return;
      }
    },
    onAffirm() {
      let workWeek = this.workWeek,
        startDate = "",
        endDate = "",
        workData = [],
        workIdData = [];
      workData = workWeek.filter(item => {
        //筛选所有选中的日期
        return item.checked === true ? item.value : false;
      });
      if (workData.length > 0) {
        let startDay = this.startTime.split(":");
        let endDay = this.endTime.split(":");
        if (Number(startDay[0]) < Number(endDay[0])) {
          //记得加选择日期
          workData.forEach(item => {
            workIdData.push(item.value);
          });
          startDate = workData[0].title;
          endDate = workData[workData.length - 1].title;
          this.form.work_week = workIdData;
          this.form.work_start_time = this.startTime;
          this.form.work_end_time = this.endTime;
          this.businessHours = `${startDate}至${endDate} ${this.startTime}-${this.endTime}`;
          this.hoursShow = false;
        } else {
          Toast("结束时间不能大于开始时间");
        }
      } else {
        Toast("请选择店铺营业日期");
      }
    },
    toGeolocation() {
      this.$router.push(this.fun.getUrl("o2oLocation_loc", {}, { tag: "merchantsIn" }));
    },
    checkChange(event) {
      this.checkedAll = event;
    },
    workWeekOn(index) {
      this.workWeek[index].checked = !this.workWeek[index].checked; //修改选中的星期几
    },
    bindChangeTime(event) {
      const val = event.$parent.innerValue;
      if (this.timeState === 1) {
        this.startTime = val;
      }
      if (this.timeState === 2) {
        this.endTime = val;
      }
    },
    chooseTimeOn(state) {
      //切换开始和结束时间
      this.currentTime = "0:00";
      this.timeState = Number(state);
    },
    onPupop(type) {
      //打开弹窗;
      if (type === "hours") {
        this.hoursShow = true;
      } else {
        this.classifyShow = true;
      }
    },
    modelInput(event) {
      this.form.store_name = event;
    },
    DetailInput(event) {
      this.form.address = event;
    },
    ownerInput(event) {
      this.form.owner_name = event;
    },
    businessInput(event) {
      this.form.business_name = event;
    },
    staffInput(event) {
      this.form.staff_mobile = event;
    },
    mobileInput(event) {
      this.form.owner_mobile = event;
    },
    descInput(event) {
      this.form.store_desc = event;
    },
    /*vant图片上传*/
    onRead(e, flag) {
      Toast.loading({
        message: "上传中",
        forbidClick: true
      });
      this.stopButton = true;
      let fd = new FormData();

      if (flag === true) {
        fd.append("file", e); // 第一个参数字符串可以填任意命名，第二个根据对象属性来找到file
      } else {
        fd.append("file", e.file); // 第一个参数字符串可以填任意命名，第二个根据对象属性来找到file
      }
      var That = this;
      axios
        .post(this.uploadUrl, fd, {
          headers: { "Content-Type": "multipart/form-data" }
        })
        .then(response => {
          var responseData = response.data;
          if (responseData.result === 1) {
            Toast.clear();
            switch (That.selectImgIndex) {
              case 1:
                That.form.store_logo = responseData.data.img_url;
                That.stopButton = false;
                break;
              case 2:
                //门店banner
                That.form.store_banner = responseData.data.img_url;
                That.stopButton = false;
                break;
              case 3:
                //门店banner
                That.form.business_pics = responseData.data.img_url;
                That.stopButton = false;
                break;
              case 4:
                That.form.identity_front_image = responseData.data.img_url;
                That.stopButton = false;
                break;
              case 5:
                That.form.identity_back_image = responseData.data.img_url;
                That.stopButton = false;
                break;
              default:
                That.stopButton = false;
                return;
            }
          } else {
            Toast(responseData.msg);
          }
        })
        .catch(error => {
          console.log(error);
        });
    },
    multipleMethod(e, flag) {
      if (e && e.length) {
        for (let i = 0; i < e.length; i++) {
          this.onRead_1(e[i], flag);
        }
      } else {
        this.onRead_1(e, flag);
      }
    },
    // vant 多图片上传
    onRead_1(e, flag) {
      Toast.loading({
        message: "上传中",
        forbidClick: true
      });
      this.stopButton = true;
      let fd = new FormData();
      if (flag === true) {
        fd.append("file", e);
      } else {
        fd.append("file", e.file); // 第一个参数字符串可以填任意命名，第二个根据对象属性来找到file
      }
      var That = this;
      axios
        .post(this.uploadUrl, fd, {
          headers: { "Content-Type": "multipart/form-data" }
        })
        .then(response => {
          var responseData = response.data;
          if (responseData.result === 1) {
            Toast.clear();
            That.form.another_pics.push(responseData.data.img_url);
            this.stopButton = false;
          } else {
            Toast(responseData.msg);
          }
        })
        .catch(error => {
          console.log(error);
        });
    },
    removeImg_1: function(delIndex) {
      this.form.another_pics.splice(delIndex, 1);
    },
    selectIndex(i) {
      if (this.stopButton) {
        return false;
      }
      this.selectImgIndex = i;
    },
    categoryList() {
      $http.post("plugin.coupon-store.frontend.category.categoryList", {}, "正在获取").then(
        response => {
          if (response.result == 1) {
            let res = response.data;
            this.classifyList = res.list;
          } else {
            // this.$dialog.alert({message:response.msg});
            //Toast(response.msg);
          }
        },
        function(response) {
          // console.log(response);
          // error callback
        }
      );
    },
    classifyInit(index, item, arr) {
      this.classifyIndex = index;
      this.secondIndex = null;
      this.threeIndex = null;
      this.secondLevel = arr;
      this.firstCategoryItem = item;
      this.secondCategoryItem = {}; //重置其他分类选择
      this.thirdCategoryItem = {};
      this.threeLevel = [];
    },
    storeApply() {
      let json = {
        basic_info: 1
      };
      $http.post("plugin.coupon-store.frontend.apply.storeApplyPage", json, "正在获取").then(
        response => {
          if (response.result == 1) {
            let res = response.data;
            let plugin_setting = response.basic_info?.plugin_setting;
            this.applyText = res.apply_text;
            this.applyTextStatus = res.apply_text_status;
            this.applyDescName = plugin_setting.coupon_store?.apply_desc_name;
          } else {
            // this.$dialog.alert({message:response.msg});
            //Toast(response.msg);
          }
        },
        function(response) {
          // console.log(response);
          // error callback
        }
      );
    },
    onRefund() {
      if ((this.form.store_name ?? "") === "") {
        Toast("请输入商户名称");
        return;
      }
      if ((this.form.store_logo ?? "") === "") {
        Toast("请上传商户logo");
        return;
      }
      if ((this.CategoryName ?? "") === "") {
        Toast("请选择分类");
        return;
      }
      if ((this.addressName ?? "") === "") {
        Toast("请选择地区");
        return;
      }
      if ((this.streetName ?? "") === "") {
        Toast("请选择街道");
        return;
      }
      if ((this.form.address ?? "") === "") {
        Toast("请选择街道");
        return;
      }
      if ((this.form.longitude ?? "") === "" && (this.form.latitude ?? "") === "") {
        Toast("请选择定位");
        return;
      }
      if ((this.businessHours ?? "") === "") {
        Toast("请输入商户营业时间");
        return;
      }
      if ((this.form.store_mobile ?? "") === "") {
        Toast("请输入店铺电话");
        return;
      }
      if ((this.form.staff_name ?? "") === "") {
        Toast("请输入商户联系人");
        return;
      }
      if ((this.form.staff_mobile ?? "") === "") {
        Toast("请输入联系电话");
        return;
      }
      if ((this.form.business_name ?? "") === "") {
        Toast("请输入企业名称");
        return;
      }
      if ((this.form.business_pics ?? "") === "") {
        Toast("请上传营业执照");
        return;
      }
      if ((this.form.another_pics ?? "") === "") {
        Toast("请上传其他补充证件");
        return;
      }
      if ((this.form.owner_name ?? "") === "") {
        Toast("请输入运营者姓名");
        return;
      }
      if ((this.form.owner_mobile ?? "") === "") {
        Toast("请输入运营者手机号");
        return;
      }
      if ((this.form.identity_front_image ?? "") === "") {
        Toast("请上传身份证正面照");
        return;
      }
      if ((this.form.identity_back_image ?? "") === "") {
        Toast("请上传身份证背面照");
        return;
      }
      if (!this.checkedAll || this.applyTextStatus !== 1) {
        Toast("请同意入驻协议名称");
        return;
      }
      $http.post("plugin.coupon-store.frontend.apply.storeApply", this.form, "正在获取").then(
        response => {
          if (response.result == 1) {
            this._initData();
            Toast(response.msg);
            setTimeout(() => {
              this.$router.replace(this.fun.getUrl("member", {}));
            }, 1000);
          } else {
            this.$dialog.alert({ message: response.msg });
          }
        },
        function(response) {
          // console.log(response);
          // error callback
        }
      );
    }
  },
  components: {
    cTitle
  }
};
